package models;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Transient;

import play.Play;
import play.cache.Cache;
import play.db.jpa.Model;

@Entity(name="user")
public class User extends Model{
    
    public User() {
        
    }
    
    public User(Long userid) {
        this.id = userid;
    }

    public static Long NOT_EXIST_USER = null;
    
    public final static String ADMIN_USERNAME = "admin.username";
    public final static String ADMIN_PASSWORD = "admin.password";
    
    
    public static long ADMIN = 0;
    
    public static String USER_CACHE_PREFIX = "user-";
    
    public String name;
    
    public String password;
    
    public boolean isActive = true;
    
    @Transient
    public boolean isAdmin;
    
    public static User findUser(long userid) { 
        return findCurrentUser(Long.toString(userid));
    }
    
    public static User findCurrentUser(String userid) {
        User user = getUserFromCache(userid);
        if (user != null) {
            return user;
        }
        if (Long.valueOf(userid) == ADMIN) {
            User admin = createAdmin();
            setUserToCache(admin);
            return createAdmin();
        }
        User current = findById(Long.valueOf(userid));
        if (current != null) {
            setUserToCache(current);
        }
        return current;
       
    }
    
    public static User createAdmin() {
        User user = new User();
        user.id = ADMIN;
        user.name = Play.configuration.getProperty(ADMIN_USERNAME);
        user.isAdmin = true;
        Cache.set(USER_CACHE_PREFIX + Long.toString(user.id), user);
        return user;
    }
    
    
    
    public static User findByName(String name) {
        return User.find("name = ? and isActive = true", name).first();
    }
    
    public static User auth(String username, String password) {
        User user =  User.find("name = ? and password = ? and isActive = true", username, password).first();
        return user;
    } 
    
    public static void clearUserFromCache(Long userid) {
        Cache.delete(USER_CACHE_PREFIX + Long.toString(userid));
    }
    
    public static User getUserFromCache(String userid) { 
       return (User)Cache.get(USER_CACHE_PREFIX + userid);
    }
    
    public static void setUserToCache(User user) {
        Cache.set(USER_CACHE_PREFIX + Long.toString(user.id), user);
    }
    
    public void updatePassword(User exist, String password) {
        exist.password = password;
        exist.save();
        clearUserFromCache(exist.id);
        setUserToCache(exist);
    }
    
    public static List<User> findActiveUsers() {
        return User.find("isActive", true).fetch();
    }
    
}
